<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="数据年份" prop="year">
        <el-date-picker clearable v-model="queryParams.year" type="year" value-format="YYYY" placeholder="请选择数据年份">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="采购单价" prop="price">
        <el-input v-model="queryParams.price" placeholder="请输入采购单价" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="采购日期" prop="purchaseDate">
        <el-date-picker v-model="queryParams.purchaseDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择采购日期"
          clearable style="width: 240px" />
      </el-form-item>
      <el-form-item label="果品规格" prop="productSize">
        <el-select v-model="queryParams.productSize" placeholder="请选择果品规格" style="width:240px">
          <el-option v-for="dict in product_spec" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产区" prop="productAreaId">
        <el-select v-model="queryParams.productAreaId" placeholder="请选择产区" style="width: 240px">
          <el-option v-for="dict in product_area" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="种植主体" prop="planterId">
        <el-select v-model="queryParams.planterId" placeholder="请选择种植主体" style="width: 240px">
          <el-option v-for="planter in planterList" :key="planter.planterId" :label="planter.planterName"
            :value="planter.planterId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['purchase:price:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['purchase:price:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['purchase:price:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="priceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据年份" align="center" prop="year" />
      <el-table-column label="发布人" align="center" prop="createBy" />
      <el-table-column label="产区" align="center" prop="productArea" />
      <el-table-column label="种植主体名称" align="center" prop="planterName" />
      <el-table-column label="果品规格" align="center" prop="productSize">
        <template #default="scope">
          <dict-tag :options="product_spec" :value="scope.row.productSize" />
        </template>
      </el-table-column>
      <el-table-column label="果品采购单价" align="center" prop="price" />
      <el-table-column label="生效时间" align="center" prop="effectiveTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.effectiveTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="失效时间" align="center" prop="expirationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expirationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:price:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:price:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改每日销售单价记录对话框 -->
    <el-dialog :title="title" v-model="open" width="850px" append-to-body>
      <el-form ref="priceRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="数据年份" prop="year">
              <el-date-picker clearable v-model="form.year" type="year" value-format="YYYY" placeholder="请选择数据年份">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="renderField(true, true)" label="产区" prop="productAreaId">
              <el-select v-model="form.productAreaId" placeholder="请选择产区" @blur="getPlanterList">
                <el-option v-for="dict in product_area" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item v-if="renderField(true, true)" label="所在县" prop="county">
              <el-select v-model="form.productAreaId" placeholder="请选择所在县" @blur="getPlanterList">
                <el-option v-for="dict in product_area" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item v-if="renderField(true, true)" label="种植主体" prop="planterId">
              <el-select v-model="form.planterId" placeholder="请选择种植主体" filterable multiple collapse-tags
                collapse-tags-tooltip :max-collapse-tags="6">
                <el-option v-for="planter in planterList" :key="planter.planterId"
                  :label="`${planter.county} - ${planter.planterName}`" :value="planter.planterId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="果品规格" prop="productSize">
              <el-select v-model="form.productSize" placeholder="请选择果品规格" multiple collapse-tags collapse-tags-tooltip
                :max-collapse-tags="6">
                <el-option v-for="dict in product_spec" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="renderField(true, true)" label="收购单价" prop="price">
              <el-input v-model="form.price" placeholder="请输入收购单价"><template #append>元/斤</template></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="renderField(true, true)" label="收购日期" prop="purchaseDate">
              <el-date-picker clearable v-model="form.purchaseDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择收购日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="renderField(true, false)" label="生效时间" prop="effectiveTime">
              <el-time-picker clearable v-model="effectiveTime" placeholder="请选择生效时间点" value-format="HH:mm:ss" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item v-if="renderField(true, true)" label="备注" prop="memo">
              <el-input v-model="form.memo" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Price">
import { listPrice, getPrice, delPrice, addPrice, updatePrice } from "@/api/purchase/price";
import { listPlanter } from "@/api/base/planter";
import dayjs from 'dayjs';

const { proxy } = getCurrentInstance();
const { product_spec, product_area } = proxy.useDict('product_spec', 'product_area');

const priceList = ref([]);
const planterList = ref([])
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const effectiveTime = ref("");
const currentYear = dayjs().year().toString();

const data = reactive({
  form: {
    purchasePriceId: null,
    year: currentYear,
    price: null,
    purchaseDate: null,
    productSize: [],
    purchasePriceId: null,
    planterId: [],
    productAreaId: [],
    productArea: null,
    effectiveTime: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    year: currentYear,
    price: null,
    purchaseDate: null,
    productSize: null,
    planterId: null,
    productAreaId: null,
  },
  rules: {
    year: [{ required: true, message: "数据归属年份不能为空", trigger: "blur" }],
    productAreaId: [{ required: true, message: "产区不能为空", trigger: "blur" }],
    planterId: [{ required: true, message: "种植主体不能为空", trigger: "blur" }],
    productSize: [{ required: true, message: "果品规格不能为空", trigger: "blur" }],
    price: [{ required: true, message: "收购单价不能为空", trigger: "blur" }],
    purchaseDate: [{ required: true, message: "收购日期不能为空", trigger: "blur" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询每日采购价记录列表 */
function getList() {
  loading.value = true;
  listPrice(queryParams.value).then(response => {
    priceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    purchasePriceId: null,
    year: currentYear,
    price: null,
    purchaseDate: null,
    productSize: [],
    purchasePriceId: null,
    planterId: [],
    productAreaId: [],
    productArea: null,
    effectiveTime: null
  };
  effectiveTime.value = "00:00:00";
  proxy.resetForm("priceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.purchasePriceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加每日采购价记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _recordId = row.purchasePriceId;
  getPrice(_recordId).then(response => {
    form.value.year = response.data.year.toString();
    form.value.purchasePriceId = response.data.purchasePriceId;
    form.value.price = response.data.price;
    form.value.purchaseDate = dayjs(response.data.purchaseDate).format('YYYY-MM-DD');
    form.value.createBy = response.data.createBy;
    form.value.createTime = response.data.createTime;
    const productSizeStr = response.data.productSize
    const productSizeList = productSizeStr.split(',');
    form.value.productSize = productSizeList;
    form.value.planterId = [response.data.planterId];
    form.value.planterName = response.data.planterName;
    form.value.productArea = response.data.productArea;
    form.value.productAreaId = response.data.productAreaId.toString();
    const effectiveTimeObj = computed(() => dayjs(response.data.effectiveTime).format('HH:mm:ss'));
    effectiveTime.value = effectiveTimeObj.value;
    console.log("effectiveTime.value", effectiveTime.value);
    open.value = true;
    title.value = "修改每日采购价记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["priceRef"].validate(valid => {
    if (valid) {
      const combined = dayjs(`${form.value.purchaseDate}T${effectiveTime.value}`)
      const fullDatetime = combined.format('YYYY-MM-DDTHH:mm:ssZ');
      form.value.effectiveTime = fullDatetime;
      if (form.value.purchasePriceId != null) {
        const planterId = form.value.planterId[0];
        const editModel = {
          "purchasePriceId": form.value.purchasePriceId,
          "year": form.value.year,
          "createBy": form.value.createBy,
          "createTime": form.value.createTime,
          "price": form.value.price,
          "purchaseDate": form.value.purchaseDate,
          "productSize": form.value.productSize.join(','),
          "planterId": planterId,
          "planterName": form.value.plantName,
          "productArea": form.value.productArea,
          "productAreaId": form.value.productAreaId,
          "effectiveTime":form.value.effectiveTime,
          "expirationTime": form.value.expirationTime,
          "memo": form.value.memo
        }
        updatePrice(editModel).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPrice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recordIds = row.purchasePriceId || ids.value;
  proxy.$modal.confirm('是否确认删除每日采购价记录编号为"' + _recordIds + '"的数据项？').then(function () {
    return delPrice(_recordIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('purchase/price/export', {
    ...queryParams.value
  }, `price_${new Date().getTime()}.xlsx`);
}

/** 是否渲染字段 */
function renderField(insert, edit) {
  return form.value.recordId == null ? insert : edit;
}

/** 读取种植主体list */
function getPlanterList(e) {
  loading.value = true;
  const productAreaId = null;
  if (e) {
    productAreaId = e;
  }
  const planterQueryParams = {
    pageNum: 1,
    pageSize: 1000,
    year: form.value.year,
    planterName: null,
    planterType: null,
    county: null,
    productAreaId: productAreaId
  }
  listPlanter(planterQueryParams.value).then(response => {
    planterList.value = response.rows;
    loading.value = false;
  });
}

getPlanterList();
getList();
</script>